import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import CoreLayout from 'containers/layout'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { getFlagValue, getPageFlag, getPostData } from 'services/utils'
import { Form, Input, Button, Icon, message, Card, Popconfirm } from 'antd'
import { protoActions } from 'reduxs'
import Ellipsis from 'ant-design-pro/lib/Ellipsis'
import _ from 'lodash'
import moment from 'moment'
import 'styles/account.scss'

const FormItem = Form.Item
const accessFlag = getPageFlag('/proto-role/user-info', 'access')
const modifyFlag = getPageFlag('/proto-role/user-info', 'modify')
const bannedFlag = getPageFlag('/proto-role/user-info', 'banned')
const gagFlag = getPageFlag('/proto-role/user-info', 'gag')

@Form.create()
class AdvancedSearchForm extends PureComponent {

  static propTypes = {
    onSubmit: PropTypes.func,
    loading: PropTypes.bool,
    Values: PropTypes.object,
  }
  
  static defaultProps = {
    onSubmit: () => null,
    loading: false,
    Values: {},
  }

  constructor (props) {
    super(props)
  }

  render () {
    const { form, loading, Values } = this.props
    const { getFieldDecorator } = form
    return (
      <Form
        className="ant-advanced-search-form"
        onSubmit={this.handleSubmit}
        >
        <div className="content">
          <FormItem 
            label={(<span style={{ width: 80, display: 'inline-block' }}>角色ID/昵称</span>)}
            >
            {getFieldDecorator('roleId', {
              rules: [
                { required: true, message: `角色ID/昵称 不能为空!` }
              ],
              initialValue: Values.roleId || null
            })(
                <Input style={{ width: 300 }} />
            )}
          </FormItem>
          <FormItem style={{ marginLeft: 20 }}>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading} 
              >
              查询
            </Button>
          </FormItem>
        </div>
      </Form>
    )
  }

  handleSubmit = (e) => {
    e && e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.onSubmit(values)
      }
    })
  }
}

@connect(
  state => ({
    auth                : state.Passport.auth,
    rtsp_key            : state.Passport.rtsp_key,
    listData            : state.Proto.listData,
    postDataPending     : state.Proto.postDataPending,
    postDataError       : state.Proto.postDataError,
    postDataMessage     : state.Proto.postDataMessage,
    postData            : state.Proto.postData,
    postDataProto       : state.Proto.postDataProto,
    MODIFY_ROLE_TYPE    : state.Proto.MODIFY_ROLE_TYPE
  }),
  dispatch => ({
    actions: bindActionCreators({ 
      ...protoActions
    }, dispatch)
  })
)
export default class UserInfo extends PureComponent {

  state = {
    editMode: ''
  }

  componentDidMount () {
    this.props.actions.getlist()
  }
  
  componentWillReceiveProps (nextProps) {
    const { postDataError, postDataMessage, postDataProto, postData, rtsp_key } = nextProps
    if (rtsp_key !== this.props.rtsp_key) {
      return
    }
    if (['user-info', 'modify-role', 'banned-role', 'gag-role'].indexOf(postDataProto) > -1 && postDataError !== -1) {
      this.setState({ editMode: '' })
      ;[404, 1000].indexOf(postDataError) > -1 && message.error('查询失败，与服务器失去联系！')
      postDataError === 500 && message.error('查询失败，服务器出现内部故障！')
      if (postDataProto === 'user-info' && postDataError !== this.props.postDataError) {
        const { BodyData } = getPostData(postData, 'user-info')
        _.isEmpty(BodyData) && postDataError > 1000 && message.error('查询不到该玩家！')
      }
    }
  }

  render () {
    const { location, auth, postData, listData, MODIFY_ROLE_TYPE, postDataPending, postDataProto } = this.props
    
    const options = {
      location,
      pageCode: accessFlag.value,
      breadcrumb: [
        { name: '主页', link: '/' },
        { name: '玩家信息类' },
        { name: '玩家数据' }
      ],
    }
    const { PostOptions, BodyData } = getPostData(postData, 'user-info')
    let protoOptions = null
    if (listData) {
      let protoData = _.find(listData, o => o.name === 'modify-role')
      if (protoData.options) {
        protoOptions = protoData.options.type || null
      }
    }
    let roleId = getRoleId(BodyData)
    return (
      <CoreLayout {...options}>
        <AdvancedSearchForm 
          onSubmit={this.handleSubmit}
          loading={postDataPending && postDataProto === 'user-info'}
          Values={PostOptions}
        />
        <div style={{ display: 'flex', flexWrap: 'wrap', flexDirection: 'row' }}>
          {!_.isEmpty(BodyData) && BodyData.map((item, i) => {
            let itemData = _.zipObject(['name', 'value'], item.split(';'))
            let itemDataValue = itemData.value
            if (/^(\d){3,}$/.test(itemData.value) && i > 0) {
              itemDataValue = parseInt(itemDataValue).toLocaleString()
            }
            let actions = [null, null, null]
            if (/^(帐号状态)/.test(item)) {
              let bannedName = itemDataValue === '封号' ? '解封' : '封号'
              let gagName = itemDataValue === '禁言' ? '解禁' : '禁言'
              actions = [
                (
                  <a onClick={() => this.props.actions.postData('user-info', { roleId }, this.props.rtsp_key)}>
                    <Icon type="reload" /> 刷新
                  </a>
                ), 
                (
                  <Popconfirm
                    title={`确定要对该用户进行${bannedName}处理吗？`}
                    onConfirm={this.handleBannedRole.bind(this, roleId)}
                    >
                    <a disabled={getFlagValue(auth, bannedFlag.value, null)}>
                      <Icon type="lock" /> {bannedName}
                    </a>
                  </Popconfirm>
                ), (
                  <Popconfirm
                    title={`确定要对该用户进行${gagName}处理吗？`}
                    onConfirm={this.handleGagRole.bind(this, roleId)}
                    >
                    <a disabled={getFlagValue(auth, gagFlag.value, null)}>
                      <Icon type="disconnect" /> {gagName}
                    </a>
                  </Popconfirm>
                )]
            }
            let modfiyOptions = _.isString(protoOptions) ? MODIFY_ROLE_TYPE : protoOptions
            if (modfiyOptions && _.values(modfiyOptions).indexOf(itemData.name) > -1) {
              actions = [
                (
                  <a onClick={() => this.props.actions.postData('user-info', { roleId }, this.props.rtsp_key)}>
                    <Icon type="reload" /> 刷新
                  </a>
                ), 
                (
                  <a 
                    onClick={() => this.setState({ editMode: itemData.name === this.state.editMode ? '' : itemData.name })}
                    disabled={getFlagValue(auth, modifyFlag.value, null)}
                    >
                    <Icon type="edit" /> 编辑
                  </a>
                ), 
                null
              ]
            }
            return (
              <Card
                key={i}
                style={{ width: 450, margin: 10, height: 185 }}
                actions={actions}
                >
                <Card.Meta
                  style={{ height: 96 }}
                  title={itemData.name}
                  description={_.values(modfiyOptions).indexOf(this.state.editMode) > -1 && this.state.editMode === itemData.name
                    ? (
                      <ModfiyInputUnit 
                        value={itemData.value} 
                        name={itemData.name} 
                        onSubmit={this.handleModfiyRole.bind(this, roleId, getOptionKey(itemData.name, modfiyOptions))}
                        loading={postDataPending && postDataProto === 'modify-role'}
                        />
                    ) 
                    : (
                      <Ellipsis length={34} tooltip>{itemDataValue}</Ellipsis>
                    )
                  }
                  />
              </Card>
            )
          })}
        </div>
      </CoreLayout>
    )
  }

  handleSubmit = (values) => {
    this.props.actions.postData('user-info', values, this.props.rtsp_key)
  }

  handleBannedRole = (roleId) => {
    this.props.actions.postData('banned-role', { roleId }, this.props.rtsp_key)
  }

  handleGagRole = (roleId) => {
    this.props.actions.postData('gag-role', { roleId }, this.props.rtsp_key)
  }

  handleModfiyRole = (roleId, type, param) => {
    this.props.actions.postData('modify-role', { roleId, type, param }, this.props.rtsp_key)
    
  }
}

@Form.create()
class ModfiyInputUnit extends PureComponent {

  static propTypes = {
    name: PropTypes.string,
    value: PropTypes.string,
    onSubmit: PropTypes.func,
    loading: PropTypes.bool
  }
  
  static defaultProps = {
    name: '',
    value: '',
    onSubmit: () => null,
    loading: false
  }

  render () {
    const { form, value, name, loading } = this.props
    const { getFieldDecorator } = form
    return (
      <Form
        layout="inline"
        onSubmit={this.handleSubmit}
        >
        <FormItem
          >
          {getFieldDecorator('proto', {
            rules: [
              { required: true, message: `${name}值 不能为空!` }
            ],
            initialValue: value
          })(
              <Input style={{ width: 260 }} />
          )}
        </FormItem>
        <FormItem style={{ marginLeft: 20 }}>
          <Button 
            type="primary" 
            htmlType="submit" 
            loading={loading} 
            >
            修改
          </Button>
        </FormItem>
      </Form>
    )
  }

  handleSubmit = (e) => {
    e && e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.onSubmit(values.proto)
      }
    })
  }
}

const getRoleId = (data) => {
  if (!data || !_.isArray(data)) {
    return ''
  }
  return data[0].replace(/^([^;]+[;])/, '')
}

const getOptionKey = (value, options) => {
  let key = 0
  for (let item in options) {
    if (options[item] === value) {
      key = item
      break
    }
  }
  return key
}